package com.emergency.service.impl;


import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.collection.CollectionUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.emergency.config.BusinessException;
import com.emergency.constant.SuppliesPointStatusEnum;
import com.emergency.data.entity.*;
import com.emergency.data.param.*;
import com.emergency.data.vo.*;
import com.emergency.http.DefaultResponseCode;
import com.emergency.mapper.*;
import com.emergency.service.AffectedPointService;
import com.emergency.util.SMSUtil;
import com.spatial4j.core.context.SpatialContext;
import com.spatial4j.core.distance.DistanceUtils;
import com.spatial4j.core.shape.Rectangle;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.util.*;
import java.util.stream.Collectors;

/**
 * (AffectedPoint)受灾点服务实现类
 *
 * @author makejava
 * @since 2020-10-09
 */
@Service
public class AffectedPointImpl extends ServiceImpl<AffectedPointMapper, AffectedPoint> implements AffectedPointService {

    @Value("${serverUrl}")
    private String linkAddress;

    @Resource
    private AffectedPointMapper affectedPointMapper;
    @Resource
    private AffectedRescueTeamMapper affectedRescueTeamMapper;
    @Resource
    private RescueTeamMapper rescueTeamMapper;
    @Resource
    private AffectedSettlementMapper affectedSettlementMapper;
    @Resource
    private AffectedEmergencySuppliesMapper affectedEmergencySuppliesMapper;
    @Resource
    private EmergencySuppliesPointMapper emergencySuppliesPointMapper;
    @Resource
    private EmergencyPointSuppliesMapper emergencyPointSuppliesMapper;
    @Resource
    private AffectedSuppliesReserveMapper affectedSuppliesReserveMapper;
    @Resource
    private SettlementPointMapper settlementPointMapper;
    @Resource
    private StreetMapper streetMapper;
    @Resource
    private VillageMapper villageMapper;
    @Resource
    private SuppliesTypeMapper suppliesTypeMapper;
    @Resource
    private TeamTypeMapper teamTypeMapper;
    @Resource
    private AffectedExpertNoticeMapper affectedExpertNoticeMapper;
    @Resource
    private ExpertGroupMapper expertGroupMapper;
    @Resource
    private DutiesMapper dutiesMapper;
    @Resource
    private IndustryMapper industryMapper;
    @Resource
    private AffectedSuppliesDemandMapper affectedSuppliesDemandMapper;


    @Override
    public List<AffectedPointVO> getAffectedPointList() {

        return affectedPointMapper.selectList(null).stream().map(c -> {
            AffectedPointVO vo = new AffectedPointVO();
            vo.setId(c.getId());
            vo.setName(c.getName());
            vo.setMapCenterX(c.getMapCenterX());
            vo.setMapCenterY(c.getMapCenterY());
            return vo;
        }).collect(Collectors.toList());
    }

    @Override
    public AffectedPointDispatchVO getAffectedPointDetails(Long id) {
        AffectedPoint affectedPoint = affectedPointMapper.selectById(id);
        AffectedPointDispatchVO affectedPointDispatchVO = new AffectedPointDispatchVO();
        if (affectedPoint != null) {
            affectedPointDispatchVO.setId(affectedPoint.getId());
            affectedPointDispatchVO.setName(affectedPoint.getName());
            affectedPointDispatchVO.setAddress(affectedPoint.getAddress());
            affectedPointDispatchVO.setScheduleScope(affectedPoint.getScheduleScope());
            affectedPointDispatchVO.setArea(affectedPoint.getArea());
            affectedPointDispatchVO.setPeopleCount(affectedPoint.getPeopleCount());
            affectedPointDispatchVO.setAffectedCount(affectedPoint.getAffectedCount());
            affectedPointDispatchVO.setScheduleCount(affectedPoint.getScheduleCount());
            affectedPointDispatchVO.setMapInfo(affectedPoint.getMapInfo());
            affectedPointDispatchVO.setStatus(affectedPoint.getStatus());
            affectedPointDispatchVO.setType(affectedPoint.getType());

            List<RescueTeamDispatchVO> rescueTeamList = new ArrayList<>();
            List<RescueTeamTypeVO> rescueTeamTypeList = new ArrayList<>();
            QueryWrapper<AffectedRescueTeam> affectedRescueTeamQuery = new QueryWrapper<>();
            affectedRescueTeamQuery.eq("affected_point_id", id);
            List<AffectedRescueTeam> rescueTeams = affectedRescueTeamMapper.selectList(affectedRescueTeamQuery);
            if (rescueTeams != null && rescueTeams.size() > 0) {
                rescueTeams.forEach(c -> {
                    RescueTeamDispatchVO rescueTeamDispatchVO = new RescueTeamDispatchVO();
                    rescueTeamDispatchVO.setId(c.getId());
                    rescueTeamDispatchVO.setTeamId(c.getRescueTeamId());
                    rescueTeamDispatchVO.setTeamTypeId(c.getRescueTeamType());
                    rescueTeamDispatchVO.setPolylineJson(c.getPolylineJson());
                    RescueTeam rescueTeam = rescueTeamMapper.selectById(c.getRescueTeamId());
                    if (rescueTeam != null) {
                        rescueTeamDispatchVO.setTeamName(rescueTeam.getTeamName());
                        rescueTeamDispatchVO.setX(rescueTeam.getX());
                        rescueTeamDispatchVO.setY(rescueTeam.getY());
                        rescueTeamDispatchVO.setScheduleCount(rescueTeam.getNumber());
                    }
                    rescueTeamDispatchVO.setCount(c.getScheduleCount());
                    rescueTeamList.add(rescueTeamDispatchVO);
                });
                if (CollectionUtil.isNotEmpty(rescueTeamList)) {
                    Map<Long, List<RescueTeamDispatchVO>> collect = rescueTeamList.stream().collect(Collectors.groupingBy(RescueTeamDispatchVO::getTeamTypeId));
                    collect.forEach((x,y)->{
                        QueryWrapper<RescueTeam> query = new QueryWrapper<>();
                        query.eq("team_type_id", x);
                        List<RescueTeam> rescueTeams1 = rescueTeamMapper.selectList(query);
                        RescueTeamTypeVO rescueTeamTypeVO = new RescueTeamTypeVO();
                        rescueTeamTypeVO.setRescueTeamType(x);
                        List<RescueTeamDispatchVO> rescueTeamDispatchVOS = collect.get(x);
                        rescueTeamTypeVO.setRescueTeamList(rescueTeamDispatchVOS);
                        rescueTeamTypeVO.setRescueTeamAllList(rescueTeams1);
                        rescueTeamTypeList.add(rescueTeamTypeVO);
                    });
                    affectedPointDispatchVO.setRescueTeamTypeList(rescueTeamTypeList);
                }
            }

            List<SettlementDispatchVO> settlementList = new ArrayList<>();
            QueryWrapper<AffectedSettlement> affectedSettlementQuery = new QueryWrapper<>();
            affectedSettlementQuery.eq("affected_point_id", id);
            List<AffectedSettlement> affectedSettlements = affectedSettlementMapper.selectList(affectedSettlementQuery);
            if (affectedSettlements != null && affectedSettlements.size() > 0) {
                affectedSettlements.forEach(c -> {
                    SettlementDispatchVO settlementDispatchVO = new SettlementDispatchVO();
                    settlementDispatchVO.setId(c.getId());
                    settlementDispatchVO.setSettlementId(c.getRescueSettlementId());
                    SettlementPoint settlementPoint = settlementPointMapper.selectById(c.getRescueSettlementId());
                    if(settlementPoint != null) {
                        settlementDispatchVO.setCapacity(settlementPoint.getCapacity());
                    } else {
                        settlementDispatchVO.setCapacity(0);
                    }
                    settlementDispatchVO.setSiteName(c.getRescueSettlementName());
                    settlementDispatchVO.setCount(c.getSettlementCount());
                    settlementDispatchVO.setPolylineJson(c.getPolylineJson());
                    settlementDispatchVO.setX(settlementPoint.getX());
                    settlementDispatchVO.setY(settlementPoint.getY());
                    settlementList.add(settlementDispatchVO);
                });
            }

            List<SuppliesDispatchVO> suppliesList = new ArrayList<>();
            QueryWrapper<AffectedEmergencySupplies> affectedEmergencySuppliesQuery = new QueryWrapper<>();
            affectedEmergencySuppliesQuery.eq("affected_point_id", id);
            List<AffectedEmergencySupplies> affectedEmergencySupplies = affectedEmergencySuppliesMapper.selectList(affectedEmergencySuppliesQuery);
            if (affectedEmergencySupplies != null && affectedEmergencySupplies.size() > 0) {
                affectedEmergencySupplies.forEach(c -> {
                    SuppliesDispatchVO suppliesDispatchVO = new SuppliesDispatchVO();
                    suppliesDispatchVO.setId(c.getId());
                    suppliesDispatchVO.setSuppliesId(c.getRescueEmergencySuppliesId());
                    suppliesDispatchVO.setPolylineJson(c.getPolylineJson());
                    EmergencySuppliesPoint emergencySuppliesPoint = emergencySuppliesPointMapper.selectById(c.getRescueEmergencySuppliesId());
                    if (emergencySuppliesPoint != null) {
                        suppliesDispatchVO.setSuppliesName(emergencySuppliesPoint.getPointName());
                    };
                    suppliesDispatchVO.setX(emergencySuppliesPoint.getX());
                    suppliesDispatchVO.setY(emergencySuppliesPoint.getY());

                    List<SuppliesReserveDispatchVO> suppliesReserveList = new ArrayList<>();
                    QueryWrapper<AffectedSuppliesReserve> affectedSuppliesReserveQuery = new QueryWrapper<>();
                    affectedSuppliesReserveQuery.eq("affected_point_id", id);
                    List<AffectedSuppliesReserve> affectedSuppliesReserves = affectedSuppliesReserveMapper.selectList(affectedSuppliesReserveQuery);
                    if (affectedSuppliesReserves != null && affectedSuppliesReserves.size() > 0) {
                        affectedSuppliesReserves.forEach(d -> {
                            SuppliesReserveDispatchVO suppliesReserveDispatchVO = new SuppliesReserveDispatchVO();
                            suppliesReserveDispatchVO.setId(d.getId());
                            suppliesReserveDispatchVO.setReserveId(d.getSuppliesReserveId());
                            suppliesReserveDispatchVO.setReserveName(d.getSuppliesReserveName());
                            suppliesReserveDispatchVO.setCount(d.getScheduleCount());
                            suppliesReserveDispatchVO.setRescueEmergencySuppliesId(d.getRescueEmergencySuppliesId());
                            if(d.getRescueEmergencySuppliesName() != null && !"".equals(d.getRescueEmergencySuppliesName())){
                                suppliesReserveDispatchVO.setRescueEmergencySuppliesName(d.getRescueEmergencySuppliesName());
                            } else {
                                EmergencySuppliesPoint emergencySuppliesPoint2 = emergencySuppliesPointMapper.selectById(c.getRescueEmergencySuppliesId());
                                if(emergencySuppliesPoint2 != null) {
                                    suppliesReserveDispatchVO.setRescueEmergencySuppliesName(emergencySuppliesPoint2.getPointName());
                                }
                            }
                            //查询物资储备信息
                            EmergencyPointSupplies supplies = emergencyPointSuppliesMapper.selectById(d.getSuppliesReserveId());
                            if (supplies != null) {
                                SuppliesType suppliesType = suppliesTypeMapper.selectById(supplies.getSuppliesTypeId());
                                if (suppliesType != null) {
                                    suppliesReserveDispatchVO.setSpecificationName(suppliesType.getSuppliesTypeName());
                                    suppliesReserveDispatchVO.setScheduleCount(supplies.getQuantity());
                                    suppliesReserveDispatchVO.setSuppliesTypeId(supplies.getSuppliesTypeId());
                                }
                            }
                            suppliesReserveList.add(suppliesReserveDispatchVO);
                        });
                    }
                    suppliesDispatchVO.setSuppliesReserveList(suppliesReserveList);
                    suppliesList.add(suppliesDispatchVO);
                });
            }


            QueryWrapper dqw = new QueryWrapper();
            dqw.eq("affected_point_id", affectedPoint.getId());
            List<AffectedSuppliesDemand> demandList = affectedSuppliesDemandMapper.selectList(dqw);

            affectedPointDispatchVO.setSettlementList(settlementList);
            affectedPointDispatchVO.setSuppliesList(suppliesList);
            affectedPointDispatchVO.setAffectedSuppliesDemandList(demandList);

        }
        return affectedPointDispatchVO;
    }

    @Override
    public boolean addAffectedPoint(AffectedPointParam affectedPointParam) {
        AffectedPoint affectedPoint = new AffectedPoint();
        BeanUtil.copyProperties(affectedPointParam, affectedPoint);
        int l = affectedPointMapper.insert(affectedPoint);
        if (l > 0) {
            return true;
        }
        return false;
    }

    @Override
    @Transactional
    public boolean delAffectedPoint(Long id) {
        AffectedPoint affectedPoint = affectedPointMapper.selectById(id);
        if(affectedPoint != null) {
            QueryWrapper<AffectedRescueTeam> affectedRescueTeamQuery = new QueryWrapper<>();
            affectedRescueTeamQuery.eq("affected_point_id", id);
            List<AffectedRescueTeam> rescueTeams = affectedRescueTeamMapper.selectList(affectedRescueTeamQuery);
            if(rescueTeams != null && rescueTeams.size() > 0) {
                rescueTeams.forEach(c->{
                    RescueTeam rescueTeam = rescueTeamMapper.selectById(c.getRescueTeamId());
                    if(rescueTeam != null) {
                        rescueTeam.setDispatchCount(0);
                        rescueTeam.setStatus(0);
                        rescueTeamMapper.updateById(rescueTeam);
                    }
                    affectedRescueTeamMapper.deleteById(c);
                });
            }

            QueryWrapper<AffectedSettlement> affectedSettlementQuery = new QueryWrapper<>();
            affectedSettlementQuery.eq("affected_point_id", id);
            List<AffectedSettlement> affectedSettlements = affectedSettlementMapper.selectList(affectedSettlementQuery);
            if(affectedSettlements != null && affectedSettlements.size() > 0) {
                affectedSettlements.forEach(c->{
                    SettlementPoint settlementPoint = settlementPointMapper.selectById(c.getRescueSettlementId());
                    if(settlementPoint != null) {
                        settlementPoint.setDispatchCount(0);
                        settlementPoint.setStatus(0);
                        settlementPointMapper.updateById(settlementPoint);
                    }
                    affectedSettlementMapper.deleteById(c);
                });
            }

            QueryWrapper<AffectedEmergencySupplies> affectedEmergencySuppliesQuery = new QueryWrapper<>();
            affectedEmergencySuppliesQuery.eq("affected_point_id", id);
            List<AffectedEmergencySupplies> affectedEmergencySupplies = affectedEmergencySuppliesMapper.selectList(affectedEmergencySuppliesQuery);
            if(affectedEmergencySupplies != null && affectedEmergencySupplies.size() > 0) {
                affectedEmergencySupplies.forEach(c->{
                    EmergencySuppliesPoint emergencySuppliesPoint = emergencySuppliesPointMapper.selectById(c.getRescueEmergencySuppliesId());
                    if(emergencySuppliesPoint != null) {
                        emergencySuppliesPoint.setStatus(0);
                        emergencySuppliesPointMapper.updateById(emergencySuppliesPoint);
                    }
                    affectedEmergencySuppliesMapper.deleteById(c);
                });
            }
            affectedPoint.setDeleteFlag(1);
            int i = affectedPointMapper.deleteById(affectedPoint);
            if(i > 0) {
                return true;
            }
        }
        return false;
    }

    @Override
    public Map<String, Object> scopeScheduleSearch(Long affectedPointId, Integer scheduleScope) {
        //这个算法存在，搜索出来的结果可能会存在超过1公里的，需要再次过滤。如果对精度没有严格要求，可以跳过。
        scheduleScope = scheduleScope-1;
        Map<String, Object> map = new HashMap<>();
        AffectedPoint affectedPoint = affectedPointMapper.selectById(affectedPointId);
        if (affectedPoint != null) {
            String mapCenterX = affectedPoint.getMapCenterX();
            double lon = Double.parseDouble(mapCenterX);
            String mapCenterY = affectedPoint.getMapCenterY();
            double lat = Double.parseDouble(mapCenterY);
            SpatialContext geo = SpatialContext.GEO;
            Rectangle rectangle = geo.getDistCalc().calcBoxByDistFromPt(geo.makePoint(lon, lat), scheduleScope * DistanceUtils.KM_TO_DEG, geo, null);
            SpatialContext geo1 = SpatialContext.GEO;
            List<RescueTeamSearchVO> rescueTeamList = rescueTeamMapper.getRescueTeamByMap(rectangle.getMinX(), rectangle.getMaxX(), rectangle.getMinY(), rectangle.getMaxY());
            if(rescueTeamList != null && rescueTeamList.size() > 0){
                rescueTeamList.forEach(c->{
                    double distance = geo.calcDistance(geo1.makePoint(Double.parseDouble(c.getX()), Double.parseDouble(c.getY())), geo.makePoint(lon, lat))* DistanceUtils.DEG_TO_KM;
                    QueryWrapper<AffectedRescueTeam> affectedRescueTeamQuery = new QueryWrapper<>();
                    affectedRescueTeamQuery.eq("affected_point_id", affectedPointId);
                    affectedRescueTeamQuery.eq("rescue_team_id",c.getId());
                    Integer count = affectedRescueTeamMapper.selectCount(affectedRescueTeamQuery);
                    if(count > 0){
                        c.setIsSelected(1);
                    } else {
                        c.setIsSelected(0);
                    }
                    c.setDistance(distance);
                });
            }
            List<SettlementPoint> settlementtPointVOList = settlementPointMapper.getSettlementPointByMap(rectangle.getMinX(), rectangle.getMaxX(), rectangle.getMinY(), rectangle.getMaxY());
            List<SettlementPointSearchVO> settlementList = new ArrayList<>();
            if (settlementtPointVOList != null && settlementtPointVOList.size() > 0) {
                settlementtPointVOList.forEach(c -> {
                    double distance = geo.calcDistance(geo1.makePoint(Double.parseDouble(c.getX()), Double.parseDouble(c.getY())), geo.makePoint(lon, lat))* DistanceUtils.DEG_TO_KM;
                    SettlementPointSearchVO settlementPointSearchVO = new SettlementPointSearchVO();
                    settlementPointSearchVO.setId(c.getId());
                    settlementPointSearchVO.setSiteName(c.getSiteName());
                    settlementPointSearchVO.setAddress(c.getAddress());
                    settlementPointSearchVO.setArea(c.getArea());
                    settlementPointSearchVO.setCapacity(c.getCapacity());
                    settlementPointSearchVO.setX(c.getX());
                    settlementPointSearchVO.setY(c.getY());
                    settlementPointSearchVO.setDistance(distance);
                    Street street = streetMapper.selectById(c.getStreetId());
                    StringBuilder s = new StringBuilder();
                    if (street != null) {
                        s.append(street.getStreetName());
                    }
                    Village village = villageMapper.selectById(c.getVillageId());
                    if (village != null) {
                        s.append(village.getVillageName());
                    }
                    settlementPointSearchVO.setRegionName(s.toString());

                    QueryWrapper<AffectedSettlement> affectedSettlementQuery = new QueryWrapper<>();
                    affectedSettlementQuery.eq("affected_point_id", affectedPointId);
                    affectedSettlementQuery.eq("rescue_settlement_id",c.getId());
                    Integer count = affectedSettlementMapper.selectCount(affectedSettlementQuery);
                    if(count > 0){
                        settlementPointSearchVO.setIsSelected(1);
                    } else {
                        settlementPointSearchVO.setIsSelected(0);
                    }

                    settlementList.add(settlementPointSearchVO);
                });

            }
            List<EmergencySuppliesPoint> emergencySuppliesPointList = emergencySuppliesPointMapper.getEmergencySuppliesPointByMap(rectangle.getMinX(), rectangle.getMaxX(), rectangle.getMinY(), rectangle.getMaxY());
            List<EmergencySuppliesPointSearchVO> suppliesList = new ArrayList<>();
            if (emergencySuppliesPointList != null && emergencySuppliesPointList.size() > 0) {
                emergencySuppliesPointList.forEach(c -> {
                    double distance = geo.calcDistance(geo1.makePoint(Double.parseDouble(c.getX()), Double.parseDouble(c.getY())), geo.makePoint(lon, lat))* DistanceUtils.DEG_TO_KM;

                    EmergencySuppliesPointSearchVO emergencySuppliesPointSearchVO = new EmergencySuppliesPointSearchVO();
                    emergencySuppliesPointSearchVO.setSuppliesName(c.getPointName());
                    emergencySuppliesPointSearchVO.setAddress(c.getStorageLocation());
                    emergencySuppliesPointSearchVO.setLinkman(c.getLinkman());
                    emergencySuppliesPointSearchVO.setPhone(c.getPhone());
                    emergencySuppliesPointSearchVO.setX(c.getX());
                    emergencySuppliesPointSearchVO.setY(c.getY());
                    emergencySuppliesPointSearchVO.setId(c.getId());
                    emergencySuppliesPointSearchVO.setDistance(distance);
                    Street street = streetMapper.selectById(c.getStreetId());
                    StringBuilder s = new StringBuilder();
                    if (street != null) {
                        s.append(street.getStreetName());
                    }
                    Village village = villageMapper.selectById(c.getVillageId());
                    if (village != null) {
                        s.append(village.getVillageName());
                    }

                    QueryWrapper<AffectedEmergencySupplies> query = new QueryWrapper<>();
                    query.eq("affected_point_id", affectedPointId);
                    query.eq("rescue_emergency_supplies_id",c.getId());
                    Integer count = affectedEmergencySuppliesMapper.selectCount(query);
                    if(count > 0){
                        emergencySuppliesPointSearchVO.setIsSelected(1);
                    } else {
                        emergencySuppliesPointSearchVO.setIsSelected(0);
                    }

                    emergencySuppliesPointSearchVO.setRegionName(s.toString());
                    suppliesList.add(emergencySuppliesPointSearchVO);
                });
            }
            affectedPoint.setScheduleScope(scheduleScope);
            affectedPointMapper.updateById(affectedPoint);


            Collections.sort(rescueTeamList, new Comparator<RescueTeamSearchVO>() {
                @Override
                public int compare(RescueTeamSearchVO o1, RescueTeamSearchVO o2) {
                    Double distance = o1.getDistance();
                    Double distance1 = o2.getDistance();
                    return distance.compareTo(distance1);
                }
            });
            Collections.sort(settlementList, new Comparator<SettlementPointSearchVO>() {
                @Override
                public int compare(SettlementPointSearchVO o1, SettlementPointSearchVO o2) {
                    Double distance = o1.getDistance();
                    Double distance1 = o2.getDistance();
                    return distance.compareTo(distance1);
                }
            });
            Collections.sort(suppliesList, new Comparator<EmergencySuppliesPointSearchVO>() {
                @Override
                public int compare(EmergencySuppliesPointSearchVO o1, EmergencySuppliesPointSearchVO o2) {
                    Double distance = o1.getDistance();
                    Double distance1 = o2.getDistance();
                    return distance.compareTo(distance1);
                }
            });

            map.put("rescueTeamList",rescueTeamList);
            map.put("settlementList",settlementList);
            map.put("suppliesList",suppliesList);
        }
        return map;
    }

    @Override
    @Transactional
    public boolean scheduleScopeAffected(ScheduleScopeAffectedParam scheduleScopeAffectedParam) {
        Long affectedId = scheduleScopeAffectedParam.getAffectedId();
        List<Long> rescueTeamIds = scheduleScopeAffectedParam.getRescueTeamIds();
        List<Long> settlementIds = scheduleScopeAffectedParam.getSettlementIds();
        List<Long> suppliesIds = scheduleScopeAffectedParam.getSuppliesIds();
        List<String> rescueTeamPolyline = scheduleScopeAffectedParam.getRescueTeamPolyline();
        List<String> settlementPolyline = scheduleScopeAffectedParam.getSettlementPolyline();
        List<String> suppliesPolyline = scheduleScopeAffectedParam.getSuppliesPolyline();
        List<Integer> countList = new ArrayList<>();
        try {
            QueryWrapper<AffectedRescueTeam> query = new QueryWrapper<>();
            query.eq("affected_point_id", affectedId);
            List<AffectedRescueTeam> affectedRescueTeams = affectedRescueTeamMapper.selectList(query);
            if(affectedRescueTeams != null && affectedRescueTeams.size() > 0) {
                affectedRescueTeams.forEach(c->{
                    affectedRescueTeamMapper.deleteById(c);
                });
            }
            if(rescueTeamIds != null && rescueTeamIds.size() > 0) {
                for (int i = 0; i<rescueTeamIds.size(); i++) {
                    AffectedRescueTeam affectedRescueTeam = new AffectedRescueTeam();
                    affectedRescueTeam.setAffectedPointId(affectedId);
                    Long id = rescueTeamIds.get(i);
                    affectedRescueTeam.setRescueTeamId(id);
                    RescueTeam rescueTeam = rescueTeamMapper.selectById(id);
                    if(rescueTeam != null) {
                        rescueTeam.setDispatchCount(rescueTeam.getNumber());
                        rescueTeam.setStatus(1);
                        rescueTeamMapper.updateById(rescueTeam);
                        affectedRescueTeam.setRescueTeamType(rescueTeam.getTeamTypeId());
                        affectedRescueTeam.setScheduleCount(rescueTeam.getNumber());
                        countList.add(rescueTeam.getNumber());
                    }
                    affectedRescueTeam.setPolylineJson(rescueTeamPolyline.get(i));
                    affectedRescueTeamMapper.insert(affectedRescueTeam);
                }
            }

            QueryWrapper<AffectedSettlement> setQuery = new QueryWrapper<>();
            setQuery.eq("affected_point_id", affectedId);
            List<AffectedSettlement> affectedSettlements = affectedSettlementMapper.selectList(setQuery);
            if(affectedSettlements != null && affectedSettlements.size() > 0) {
                affectedSettlements.forEach(c->{
                    affectedSettlementMapper.deleteById(c);
                });
            }
            if(settlementIds != null && settlementIds.size() > 0) {
                for (int i = 0; i<settlementIds.size(); i++) {
                    AffectedSettlement affectedSettlement = new AffectedSettlement();
                    affectedSettlement.setAffectedPointId(affectedId);
                    Long id = settlementIds.get(i);
                    affectedSettlement.setRescueSettlementId(id);
                    SettlementPoint settlementPoint = settlementPointMapper.selectById(id);
                    if(settlementPoint != null) {
                        settlementPoint.setDispatchCount(settlementPoint.getCapacity());
                        settlementPoint.setStatus(1);
                        settlementPointMapper.updateById(settlementPoint);
                        affectedSettlement.setRescueSettlementName(settlementPoint.getSiteName());
                        Integer capacity = settlementPoint.getCapacity();
                        if(capacity != null) {
                            affectedSettlement.setSettlementCount(capacity);
                        } else {
                            affectedSettlement.setSettlementCount(0);
                        }
                    }
                    affectedSettlement.setPolylineJson(settlementPolyline.get(i));
                    affectedSettlementMapper.insert(affectedSettlement);
                }
            }

            QueryWrapper<AffectedEmergencySupplies> supQuery = new QueryWrapper<>();
            supQuery.eq("affected_point_id", affectedId);
            List<AffectedEmergencySupplies> affectedEmergencySuppliess = affectedEmergencySuppliesMapper.selectList(supQuery);
            if(affectedEmergencySuppliess != null && affectedEmergencySuppliess.size() > 0) {
                affectedEmergencySuppliess.forEach(c->{
                    affectedEmergencySuppliesMapper.deleteById(c);
                });
            }
            if(suppliesIds != null && suppliesIds.size() > 0) {
                for (int i = 0; i<suppliesIds.size(); i++) {
                    AffectedEmergencySupplies affectedEmergencySupplies = new AffectedEmergencySupplies();
                    affectedEmergencySupplies.setAffectedPointId(affectedId);
                    Long id = suppliesIds.get(i);
                    affectedEmergencySupplies.setRescueEmergencySuppliesId(id);
                    EmergencySuppliesPoint emergencySuppliesPoint = emergencySuppliesPointMapper.selectById(id);
                    if(emergencySuppliesPoint != null) {
                        emergencySuppliesPoint.setStatus(1);
                        emergencySuppliesPointMapper.updateById(emergencySuppliesPoint);
                    }
                    affectedEmergencySupplies.setPolylineJson(suppliesPolyline.get(i));
                    affectedEmergencySuppliesMapper.insert(affectedEmergencySupplies);

                    //添加物资点的物资储备数量
                    QueryWrapper epsQw = new QueryWrapper();
                    epsQw.eq("emergency_supplies_point_id",id);
                    List<EmergencyPointSupplies> suppliesList = emergencyPointSuppliesMapper.selectList(epsQw);
                    if (CollectionUtil.isNotEmpty(suppliesList)) {
                        suppliesList.forEach(item->{
                            AffectedSuppliesReserve suppliesReserve = new AffectedSuppliesReserve();
                            suppliesReserve.setAffectedPointId(affectedId);
                            suppliesReserve.setRescueEmergencySuppliesId(emergencySuppliesPoint.getId());
                            suppliesReserve.setRescueEmergencySuppliesName(emergencySuppliesPoint.getPointName());
                            suppliesReserve.setScheduleCount(item.getQuantity());
                            suppliesReserve.setSuppliesReserveId(item.getId());
                            suppliesReserve.setSuppliesReserveName(item.getSuppliesName());
                            affectedSuppliesReserveMapper.insert(suppliesReserve);

                            item.setDispatchNumber(item.getQuantity());
                            emergencyPointSuppliesMapper.updateById(item);
                        });
                    }
                }
            }
            AffectedPoint affectedPoint = affectedPointMapper.selectById(affectedId);
            if(affectedPoint != null) {
                long sum = countList.stream().reduce(Integer::sum).orElse(0);
                affectedPoint.setScheduleCount((int) sum);
                affectedPoint.setStatus(1);
                affectedPoint.setType(1);
                affectedPointMapper.updateById(affectedPoint);
            }
            return true;
        }   catch (Exception e) {
            e.printStackTrace();
            return false;
        }

    }

    @Override
    public List<TypeVO> getSuppliesTypeList() {
        QueryWrapper<SuppliesType> query = new QueryWrapper<>();
        query.eq("delete_flag", 0);
        List<SuppliesType> suppliesTypes = suppliesTypeMapper.selectList(query);
        List<TypeVO> typeVOList = new ArrayList<>();
        if (suppliesTypes != null && suppliesTypes.size() > 0) {
            suppliesTypes.forEach(c -> {
                TypeVO typeVO = new TypeVO();
                typeVO.setId(c.getId());
                typeVO.setName(c.getSuppliesTypeName());
                typeVOList.add(typeVO);
            });
        }
        return typeVOList;
    }

    @Override
    public List<TypeVO> getRescueTeamTypeList() {
        QueryWrapper<TeamType> query = new QueryWrapper<>();
        query.eq("delete_flag", 0);
        List<TeamType> teamTypes = teamTypeMapper.selectList(query);
        List<TypeVO> typeVOList = new ArrayList<>();
        if (teamTypes != null && teamTypes.size() > 0) {
            teamTypes.forEach(c -> {
                TypeVO typeVO = new TypeVO();
                typeVO.setId(c.getId());
                typeVO.setName(c.getTeamTypeName());
                typeVOList.add(typeVO);
            });
        }
        return typeVOList;
    }

    @Override
    public Map<String, Object> requiredScheduleSearchTeam(Long affectedPointId, Integer typeId) {
        Map<String, Object> map = new HashMap<>();
        QueryWrapper<RescueTeam> query = new QueryWrapper<>();
        query.eq("delete_flag", 0);
        query.eq("team_type_id", typeId);
        query.eq("status", 0);
        List<RescueTeamSearchVO> rescueTeamList = new ArrayList<>();

        AffectedPoint affectedPoint = affectedPointMapper.selectById(affectedPointId);
        if (affectedPoint != null) {
            String mapCenterX = affectedPoint.getMapCenterX();
            double lon = Double.parseDouble(mapCenterX);
            String mapCenterY = affectedPoint.getMapCenterY();
            double lat = Double.parseDouble(mapCenterY);
            SpatialContext geo = SpatialContext.GEO;
            SpatialContext geo1 = SpatialContext.GEO;
            List<RescueTeam> rescueTeams = rescueTeamMapper.selectList(query);
            if (rescueTeams != null && rescueTeams.size() > 0) {
                rescueTeams.forEach(c -> {
                    double distance = geo.calcDistance(geo1.makePoint(Double.parseDouble(c.getX()), Double.parseDouble(c.getY())), geo.makePoint(lon, lat))* DistanceUtils.DEG_TO_KM;
                    RescueTeamSearchVO rescueTeamSearchVO = new RescueTeamSearchVO();
                    rescueTeamSearchVO.setId(c.getId());
                    rescueTeamSearchVO.setTeamName(c.getTeamName());
                    rescueTeamSearchVO.setLevel(c.getLevel());
                    rescueTeamSearchVO.setNumber(c.getNumber());
                    rescueTeamSearchVO.setResponsiblePeople(c.getResponsiblePeople());
                    rescueTeamSearchVO.setPhone(c.getPhone());
                    rescueTeamSearchVO.setX(c.getX());
                    rescueTeamSearchVO.setY(c.getY());
                    rescueTeamSearchVO.setDistance(distance);
                    rescueTeamList.add(rescueTeamSearchVO);
                });
            }
        }
        Collections.sort(rescueTeamList, new Comparator<RescueTeamSearchVO>() {
            @Override
            public int compare(RescueTeamSearchVO o1, RescueTeamSearchVO o2) {
                Double distance = o1.getDistance();
                Double distance1 = o2.getDistance();
                return distance.compareTo(distance1);
            }
        });
        map.put("rescueTeamList", rescueTeamList);
        return map;
    }

    @Override
    public Map<String, Object> requiredScheduleSearchRescue(Long affectedPointId,Integer affectedCount) {
        Map<String, Object> map = new HashMap<>();
        QueryWrapper<SettlementPoint> query = new QueryWrapper<>();
        query.eq("delete_flag", 0);
        query.ge("capacity", affectedCount);
        query.eq("status", 0);
        List<SettlementPointSearchVO> settlementList = new ArrayList<>();
        AffectedPoint affectedPoint = affectedPointMapper.selectById(affectedPointId);
        if (affectedPoint != null) {
            String mapCenterX = affectedPoint.getMapCenterX();
            double lon = Double.parseDouble(mapCenterX);
            String mapCenterY = affectedPoint.getMapCenterY();
            double lat = Double.parseDouble(mapCenterY);
            SpatialContext geo = SpatialContext.GEO;
            SpatialContext geo1 = SpatialContext.GEO;
            List<SettlementPoint> settlementPoints = settlementPointMapper.selectList(query);

            //家进入选中的避灾点数据
            QueryWrapper<AffectedSettlement> setQuery = new QueryWrapper<>();
            setQuery.eq("affected_point_id", affectedPointId);
            List<AffectedSettlement> affectedSettlements = affectedSettlementMapper.selectList(setQuery);
            if(affectedSettlements != null && affectedSettlements.size() > 0) {
                List<Long> settlementsIds = affectedSettlements.stream().map(AffectedSettlement::getRescueSettlementId).collect(Collectors.toList());
                List<SettlementPoint> list = settlementPointMapper.selectBatchIds(settlementsIds);
                settlementPoints.addAll(list);
            }
            if (settlementPoints != null && settlementPoints.size() > 0) {
                settlementPoints.forEach(c -> {
                    double distance = geo.calcDistance(geo1.makePoint(Double.parseDouble(c.getX()), Double.parseDouble(c.getY())), geo.makePoint(lon, lat))* DistanceUtils.DEG_TO_KM;
                    SettlementPointSearchVO settlementPointSearchVO = new SettlementPointSearchVO();
                    settlementPointSearchVO.setId(c.getId());
                    settlementPointSearchVO.setSiteName(c.getSiteName());
                    settlementPointSearchVO.setAddress(c.getAddress());
                    settlementPointSearchVO.setArea(c.getArea());
                    settlementPointSearchVO.setCapacity(c.getCapacity());
                    Street street = streetMapper.selectById(c.getStreetId());
                    StringBuilder s = new StringBuilder();
                    if (street != null) {
                        s.append(street.getStreetName());
                    }
                    Village village = villageMapper.selectById(c.getVillageId());
                    if (village != null) {
                        s.append(village.getVillageName());
                    }
                    settlementPointSearchVO.setX(c.getX());
                    settlementPointSearchVO.setY(c.getY());
                    settlementPointSearchVO.setRegionName(s.toString());
                    settlementPointSearchVO.setDistance(distance);
                    settlementList.add(settlementPointSearchVO);
                });
            }
        }
        Collections.sort(settlementList, new Comparator<SettlementPointSearchVO>() {
            @Override
            public int compare(SettlementPointSearchVO o1, SettlementPointSearchVO o2) {
                Double distance = o1.getDistance();
                Double distance1 = o2.getDistance();
                return distance.compareTo(distance1);
            }
        });
        map.put("settlementList", settlementList);
        return map;
    }

    @Override
    public boolean expertConfirmNotice(Long noticeId) {
        AffectedExpertNotice affectedExpertNotice = affectedExpertNoticeMapper.selectById(noticeId);
        if (affectedExpertNotice != null) {
            affectedExpertNotice.setIsConfirm(1);
            int l = affectedExpertNoticeMapper.updateById(affectedExpertNotice);
            if (l > 0) {
                return true;
            }
        }
        return false;
    }

    @Override
    public List<ExpertGroupListVO> expertNoticeList(Long affectedPointId) {
        QueryWrapper<AffectedExpertNotice> query = new QueryWrapper<>();
        query.eq("delete_flag", 0);
        query.eq("affected_point_id", affectedPointId);
        List<ExpertGroupListVO> expertGroupListVOList = new ArrayList<>();
        List<AffectedExpertNotice> affectedExpertNoticeList = affectedExpertNoticeMapper.selectList(query);
        if (affectedExpertNoticeList != null && affectedExpertNoticeList.size() > 0) {
            affectedExpertNoticeList.forEach(c -> {
                ExpertGroupListVO expertGroupListVO = new ExpertGroupListVO();
                expertGroupListVO.setId(c.getId());
                expertGroupListVO.setIsConfirm(c.getIsConfirm());
                if (c.getIsConfirm() == 0) {
                    expertGroupListVO.setIsConfirmStr("未确认");
                } else {
                    expertGroupListVO.setIsConfirmStr("已确认");
                }
                ExpertGroup expertGroup = expertGroupMapper.selectById(c.getExpertId());
                if (expertGroup != null) {
                    expertGroupListVO.setName(expertGroup.getName());
                    //职称
                    Duties duties = dutiesMapper.selectById(expertGroup.getDutiesId());
                    if (duties != null) {
                        expertGroupListVO.setDutiesName(duties.getDutiesName());
                    }
                    //查询从事行业和特长
                    Industry industry = industryMapper.selectById(expertGroup.getIndustryId());
                    if (industry != null) {
                        expertGroupListVO.setIndustryName(industry.getIndustryName());
                    }

                    expertGroupListVO.setCompany(expertGroup.getCompany());
                    expertGroupListVO.setPhone(expertGroup.getPhone());
                }
                expertGroupListVOList.add(expertGroupListVO);
            });
        }
        return expertGroupListVOList;
    }
    @Override
    public boolean addExpertNotice(NoticeParam noticeParam) {
        Long affectedPointId = noticeParam.getAffectedPointId();
        AffectedPoint affectedPoint = affectedPointMapper.selectById(affectedPointId);
        if(affectedPoint != null) {
            String affectedPointName = affectedPoint.getName();
            List<Long> noticeList = noticeParam.getNoticeList();
            if(noticeList != null && noticeList.size() > 0) {
                noticeList.forEach(c->{
                    QueryWrapper<AffectedExpertNotice> query = new QueryWrapper<>();
                    query.eq("affected_point_id", affectedPointId);
                    query.eq("expert_id", c);
                    Integer i = affectedExpertNoticeMapper.selectCount(query);
                    if(i == 0) {
                        AffectedExpertNotice affectedExpertNotice = new AffectedExpertNotice();
                        affectedExpertNotice.setExpertId(c);
                        affectedExpertNotice.setAffectedPointId(affectedPointId);
                        affectedExpertNotice.setIsConfirm(0);
                        int l = affectedExpertNoticeMapper.insert(affectedExpertNotice);
                        if(l > 0) {
                            ExpertGroup expertGroup = expertGroupMapper.selectById(c);
                            if(expertGroup != null) {
                                String phone = expertGroup.getPhone();
                                SMSUtil.sendExpertSMS(phone,affectedPointName,linkAddress + "/emergency/dispatch/expert/confirmNotice?noticeId=" + affectedExpertNotice.getId());
                            }
                        }
                    }

                });
                return true;
            }
        } else {
            throw new BusinessException(DefaultResponseCode.AFFECTEDPOINTIS_NOT_EXIST);
        }
         return false;
    }

    @Transactional
    @Override
    public List<TeamVO> scheduleRequireAffectedTeam(ScheduleRequireAffectedTeamParam scheduleRequireAffectedTeamParam) {
        Long affectedId = scheduleRequireAffectedTeamParam.getAffectedId();
        List<TeamParam> rescueTeamList = scheduleRequireAffectedTeamParam.getRescueTeamList();

        List<TeamVO> teamList = new ArrayList<>();
        List<Integer> countList = new ArrayList<>();

        //删除之前保存的数据
        QueryWrapper suppliesQw = new QueryWrapper<>();
        suppliesQw.eq("affected_point_id", affectedId);
        List<AffectedRescueTeam> affectedRescueTeamList = affectedRescueTeamMapper.selectList(suppliesQw);
        if (CollectionUtil.isNotEmpty(affectedRescueTeamList)) {
            affectedRescueTeamList.forEach(item->{
                RescueTeam rescueTeam = rescueTeamMapper.selectById(item.getRescueTeamId());
                if (rescueTeam != null) {
                    rescueTeam.setDispatchCount(0);
                    rescueTeam.setStatus(0);
                    rescueTeamMapper.updateById(rescueTeam);
                }
            });
        }
        affectedRescueTeamMapper.delete(suppliesQw);


        List<String> rescueTeamPolyline = scheduleRequireAffectedTeamParam.getRescueTeamPolyline();
        if(rescueTeamList != null && rescueTeamList.size() > 0) {
            for(int i=0; i<rescueTeamList.size(); i++) {
                TeamVO teamVO = new TeamVO();
                teamVO.setScheduleCount(rescueTeamList.get(i).getScheduleCount());
                AffectedRescueTeam affectedRescueTeam = new AffectedRescueTeam();
                affectedRescueTeam.setAffectedPointId(affectedId);
                affectedRescueTeam.setRescueTeamId(rescueTeamList.get(i).getTeamId());
                affectedRescueTeam.setScheduleCount(rescueTeamList.get(i).getScheduleCount());
                RescueTeam rescueTeam = rescueTeamMapper.selectById(rescueTeamList.get(i).getTeamId());
                if(rescueTeam != null) {
                    affectedRescueTeam.setRescueTeamType(rescueTeam.getTeamTypeId());
                    teamVO.setTeamName(rescueTeam.getTeamName());
                    rescueTeam.setDispatchCount(rescueTeamList.get(i).getScheduleCount());
                    rescueTeam.setStatus(1);
                    rescueTeamMapper.updateById(rescueTeam);
                    countList.add(rescueTeamList.get(i).getScheduleCount());
                }

                affectedRescueTeam.setPolylineJson(rescueTeamPolyline.get(i));
                affectedRescueTeamMapper.insert(affectedRescueTeam);
                teamList.add(teamVO);
            }
            AffectedPoint affectedPoint = affectedPointMapper.selectById(affectedId);
            if(affectedPoint != null) {
                long sum = countList.stream().reduce(Integer::sum).orElse(0);
                affectedPoint.setScheduleCount((int) sum);
                affectedPoint.setStatus(1);
                affectedPointMapper.updateById(affectedPoint);
            }
            return teamList;
        }
        return teamList;
    }

    @Transactional
    @Override
    public List<SettlementVO> scheduleRequireAffectedSettlement(ScheduleRequireAffectedSettlementParam scheduleRequireAffectedSettlementParam) {
        Long affectedId = scheduleRequireAffectedSettlementParam.getAffectedId();
        List<SettlementParam> settlementList = scheduleRequireAffectedSettlementParam.getSettlementList();

        //删除之前保存的数据
        QueryWrapper suppliesQw = new QueryWrapper<>();
        suppliesQw.eq("affected_point_id", affectedId);
        List<AffectedSettlement> affectedRescueTeamList = affectedSettlementMapper.selectList(suppliesQw);
        if (CollectionUtil.isNotEmpty(affectedRescueTeamList)) {
            affectedRescueTeamList.forEach(item->{
                SettlementPoint settlement = settlementPointMapper.selectById(item.getRescueSettlementId());
                if (settlement != null) {
                    settlement.setDispatchCount(0);
                    settlement.setStatus(0);
                    settlementPointMapper.updateById(settlement);
                }
            });
        }
        affectedSettlementMapper.delete(suppliesQw);

        List<SettlementVO> settlementVOList = new ArrayList<>();

        List<String> settlementPolyline = scheduleRequireAffectedSettlementParam.getSettlementPolyline();
        if(settlementList != null && settlementList.size() > 0) {
            for(int i=0; i<settlementList.size(); i++) {
                SettlementVO settlementVO = new SettlementVO();
                settlementVO.setCount(settlementList.get(i).getScheduleCount());
                AffectedSettlement affectedSettlement = new AffectedSettlement();
                affectedSettlement.setAffectedPointId(affectedId);
                affectedSettlement.setRescueSettlementId(settlementList.get(i).getSettlementId());
                affectedSettlement.setSettlementCount(settlementList.get(i).getScheduleCount());
                SettlementPoint settlementPoint = settlementPointMapper.selectById(settlementList.get(i).getSettlementId());
                if(settlementPoint != null) {
                    affectedSettlement.setRescueSettlementName(settlementPoint.getSiteName());
                    settlementVO.setSettlementName(settlementPoint.getSiteName());
                    settlementPoint.setStatus(1);
                    settlementPoint.setDispatchCount(settlementList.get(i).getScheduleCount());
                    settlementPointMapper.updateById(settlementPoint);
                }
                affectedSettlement.setPolylineJson(settlementPolyline.get(i));
                affectedSettlementMapper.insert(affectedSettlement);
                settlementVOList.add(settlementVO);
            }
            AffectedPoint affectedPoint = affectedPointMapper.selectById(affectedId);
            if(affectedPoint != null) {
                affectedPoint.setStatus(1);
                affectedPointMapper.updateById(affectedPoint);
            }
            return settlementVOList;
        }
        return settlementVOList;
    }

    @Transactional
    @Override
    public List<SuppliesVO> scheduleRequireAffectedSupplies(ScheduleRequireAffectedSuppliesParam scheduleRequireAffectedSuppliesParam) {

        Long affectedId = scheduleRequireAffectedSuppliesParam.getAffectedId();
        List<SuppliesParam> suppliesList = scheduleRequireAffectedSuppliesParam.getSuppliesList();


        //删除之前保存的数据
        QueryWrapper suppliesQw = new QueryWrapper<>();
        suppliesQw.eq("affected_point_id", affectedId);
        List<AffectedSuppliesReserve> affectedRescueTeamList = affectedSuppliesReserveMapper.selectList(suppliesQw);
        if (CollectionUtil.isNotEmpty(affectedRescueTeamList)) {
            affectedRescueTeamList.forEach(item->{
                EmergencyPointSupplies settlement = emergencyPointSuppliesMapper.selectById(item.getSuppliesReserveId());
                if (settlement != null) {
                    settlement.setDispatchNumber(0);
                    emergencyPointSuppliesMapper.updateById(settlement);
                }
            });
        }
        affectedEmergencySuppliesMapper.delete(suppliesQw);
        affectedSuppliesDemandMapper.delete(suppliesQw);

        List<SuppliesVO> suppliesVOList = new ArrayList<>();

        List<String> suppliesPolyline = scheduleRequireAffectedSuppliesParam.getSuppliesPolyline();
        if(suppliesList != null && suppliesList.size() > 0) {
            for(int i=0; i< suppliesList.size(); i++) {
                AffectedEmergencySupplies affectedEmergencySupplies = new AffectedEmergencySupplies();
                affectedEmergencySupplies.setAffectedPointId(affectedId);
                Long suppliesId = suppliesList.get(i).getSuppliesId();
                affectedEmergencySupplies.setRescueEmergencySuppliesId(suppliesId);
                affectedEmergencySupplies.setPolylineJson(suppliesPolyline.get(i));
                affectedEmergencySuppliesMapper.insert(affectedEmergencySupplies);
                EmergencySuppliesPoint emergencySuppliesPoint = emergencySuppliesPointMapper.selectById(suppliesId);
                String suppliesPointName = "";
                if(emergencySuppliesPoint != null) {
                    suppliesPointName = emergencySuppliesPoint.getPointName();
                    emergencySuppliesPoint.setStatus(1);
                    emergencySuppliesPointMapper.updateById(emergencySuppliesPoint);
                }
                List<SuppliesReserveParam> suppliesReserveList = suppliesList.get(i).getSuppliesReserveList();
                if(suppliesReserveList != null && suppliesReserveList.size() > 0) {

                    String finalSuppliesPointName = suppliesPointName;
                    suppliesReserveList.forEach(c->{
                        //返回对象
                        SuppliesVO suppliesVO = new SuppliesVO();
                        suppliesVO.setCount(c.getScheduleQuantity());
                        suppliesVO.setSuppliesPointName(finalSuppliesPointName);
                        AffectedSuppliesReserve affectedSuppliesReserve = new AffectedSuppliesReserve();

                        affectedSuppliesReserve.setRescueEmergencySuppliesId(suppliesId);
                        affectedSuppliesReserve.setRescueEmergencySuppliesName(finalSuppliesPointName);
                        affectedSuppliesReserve.setAffectedPointId(affectedId);
                        Long reserveId = c.getReserveId();
                        affectedSuppliesReserve.setSuppliesReserveId(reserveId);
                        EmergencyPointSupplies emergencyPointSupplies = emergencyPointSuppliesMapper.selectById(reserveId);
                        if(emergencyPointSupplies != null) {
                            emergencyPointSupplies.setDispatchNumber(c.getScheduleQuantity());
                            emergencyPointSuppliesMapper.updateById(emergencyPointSupplies);
                            affectedSuppliesReserve.setSuppliesReserveName(emergencyPointSupplies.getSuppliesName());
                            suppliesVO.setSuppliesName(emergencyPointSupplies.getSuppliesName());
                        }
                        affectedSuppliesReserve.setScheduleCount(c.getScheduleQuantity());
                        affectedSuppliesReserveMapper.insert(affectedSuppliesReserve);
                        suppliesVOList.add(suppliesVO);
                    });
                }

            }
            AffectedPoint affectedPoint = affectedPointMapper.selectById(affectedId);
            if(affectedPoint != null) {
                affectedPoint.setStatus(1);
                affectedPointMapper.updateById(affectedPoint);
            }
            return suppliesVOList;
        }
        return suppliesVOList;
    }


    @Override
    public List<DispatchSuppliesSearchVo> requiredScheduleSearchSupplies(DispatchRequiredSuppliesParam param) {
        //查询救灾点信息
        AffectedPoint point = affectedPointMapper.selectById(param.getAffectedPointId());
        if (point == null) {
            throw new BusinessException(DefaultResponseCode.USER_NOT_EXIST);
        }
        List<DispatchSuppliesSearchVo> result = new ArrayList<>();

        //查询是否有符合要求的物资点
        List<Long> typeIdList = param.getSuppliesList().stream().map(DispatchSuppliesParam::getTypeId).collect(Collectors.toList());
        List<Long> list = emergencyPointSuppliesMapper.getRequiredSearchList(typeIdList);

        if (CollectionUtil.isEmpty(list)) {
            throw new BusinessException(DefaultResponseCode.FAIL, "当前物资点物资库存不足，请调整");
        }

        //保存按需搜索的物资数据
        param.getSuppliesList().forEach(item->{
            AffectedSuppliesDemand demand = new AffectedSuppliesDemand();
            demand.setAffectedPointId(param.getAffectedPointId());
            demand.setSuppliesReserveTypeId(item.getTypeId());
            demand.setScheduleCount(item.getCount());
            affectedSuppliesDemandMapper.insert(demand);
        });

        //处理数据排序，将完全符合要求的物资点排前面
        List<Long> tempList = new ArrayList<>();
        for (Long aLong : list) {
            Integer flagCount = 0;
            for (DispatchSuppliesParam type : param.getSuppliesList()) {
                QueryWrapper qw = new QueryWrapper();
                qw.eq("emergency_supplies_point_id", aLong);
                qw.ge("quantity", type.getCount());
                qw.eq("supplies_type_id", type.getTypeId());
                Integer whereCount = emergencyPointSuppliesMapper.selectCount(qw);
                if (whereCount > 0) {
                    flagCount++;
                }
            }
            if (flagCount == typeIdList.size()) {
                tempList.add(aLong);
                break;
            }
        }
        //如果存在完全符合物资点的数据就把list值设置为tempList
        if (CollectionUtil.isNotEmpty(tempList)) {
            list = tempList;
        }

        //物资点是否满足标记
        Map<Long, RequiredScheduleCountFlagVO> flagVOMap = new HashMap<>(param.getSuppliesList().size());
        param.getSuppliesList().forEach(item -> {
            RequiredScheduleCountFlagVO flagVO = new RequiredScheduleCountFlagVO();
            flagVO.setTypeId(item.getTypeId());
            flagVO.setRequiredCount(item.getCount());
            flagVO.setScheduleCount(0);
            flagVOMap.put(item.getTypeId(), flagVO);
        });

        //处理数据
        for (Long suppliesPointId : list) {
            EmergencySuppliesPoint suppliesPoint = emergencySuppliesPointMapper.selectById(suppliesPointId);
            //如果物资点已被调度则不是此物资点
            if (suppliesPoint.getStatus().equals(SuppliesPointStatusEnum.DISPATCHING.status())) {
                continue;
            }
            //检查 已经设置的物资数量大于所需数量则break
            Integer flagCount = 0;
            for (DispatchSuppliesParam item : param.getSuppliesList()) {
                if (flagVOMap.get(item.getTypeId()).getScheduleCount() >= flagVOMap.get(item.getTypeId()).getRequiredCount()) {
                    flagCount++;
                }
            }
            if(flagCount==param.getSuppliesList().size()){
                break;
            }

            DispatchSuppliesSearchVo vo = new DispatchSuppliesSearchVo();
            vo.setSuppliesPointId(suppliesPointId);
            vo.setSuppliesPointName(suppliesPoint.getPointName());
            vo.setPhone(suppliesPoint.getPhone());
            vo.setAddress(suppliesPoint.getStorageLocation());
            //行政区域
            StringBuilder regionName = new StringBuilder();
            Street street = streetMapper.selectById(suppliesPoint.getStreetId());
            if (street != null) {
                regionName.append(street.getStreetName());
            }
            Village village = villageMapper.selectById(suppliesPoint.getVillageId());
            if (village != null) {
                regionName.append(village.getVillageName());
            }
            vo.setRegionName(regionName.toString());
            vo.setX(suppliesPoint.getX());
            vo.setY(suppliesPoint.getY());
            //设置物资点物资储备
            List<SuppliesReserveDispatchVO> suppliesReserveList = new ArrayList<>();
            for (DispatchSuppliesParam item : param.getSuppliesList()) {

                QueryWrapper psQuery = new QueryWrapper<>();
                psQuery.eq("emergency_supplies_point_id", suppliesPointId);
                psQuery.eq("supplies_type_id", item.getTypeId());
                psQuery.orderByDesc("quantity");
                List<EmergencyPointSupplies> psList = emergencyPointSuppliesMapper.selectList(psQuery);

                for (EmergencyPointSupplies psItem : psList) {
                    //已经设置的物资数量大于所需数量则break
                    if (flagVOMap.get(item.getTypeId()).getScheduleCount() >= flagVOMap.get(item.getTypeId()).getRequiredCount()) {
                        break;
                    } else {
                        SuppliesReserveDispatchVO reserveDispatchVO = new SuppliesReserveDispatchVO();
                        reserveDispatchVO.setReserveId(psItem.getId());
                        reserveDispatchVO.setReserveName(psItem.getSuppliesName());
                        reserveDispatchVO.setScheduleCount(psItem.getQuantity());

                        //当前物资满足break
                        if (psItem.getQuantity() >= item.getCount()) {
                            RequiredScheduleCountFlagVO tempFlagVo = flagVOMap.get(item.getTypeId());
                            tempFlagVo.setScheduleCount(item.getCount());
                            flagVOMap.put(item.getTypeId(), tempFlagVo);
                            suppliesReserveList.add(reserveDispatchVO);
                            break;
                        } else {
                            RequiredScheduleCountFlagVO tempFlagVo = flagVOMap.get(item.getTypeId());
                            tempFlagVo.setScheduleCount(flagVOMap.get(item.getTypeId()).getScheduleCount() + psItem.getQuantity());
                            flagVOMap.put(item.getTypeId(), tempFlagVo);
                            suppliesReserveList.add(reserveDispatchVO);
                        }
                    }
                }
            }
            vo.setSuppliesReserveList(suppliesReserveList);
            if (CollUtil.isNotEmpty(suppliesReserveList)) {
                result.add(vo);
            }
        }

//        QueryWrapper sQuery = new QueryWrapper<>();
////        sQuery.eq("");
//        List<AffectedEmergencySupplies> suppliesList = emergencySuppliesPointMapper.selectList(sQuery);

        return result;
    }

}
